<template>
	<view class="alarm-search-container">
		<!-- 过滤条件列表 -->
		<view class="filter-list">
			<!-- 告警状态列表 -->
			<view class="filter-item">
				<view class="filter-title">告警状态</view>
				<view class="tag-options">
					<view 
						class="tag" 
						:class="{ active: selectedStatus.includes('ACTIVE') }"
						@tap="toggleStatus('ACTIVE')"
					>
						激活
					</view>
					<view 
						class="tag" 
						:class="{ active: selectedStatus.includes('CLEARED') }"
						@tap="toggleStatus('CLEARED')"
					>
						已清除
					</view>
					<view 
						class="tag" 
						:class="{ active: selectedStatus.includes('ACK') }"
						@tap="toggleStatus('ACK')"
					>
						已确认
					</view>
					<view 
						class="tag" 
						:class="{ active: selectedStatus.includes('UNACK') }"
						@tap="toggleStatus('UNACK')"
					>
						未确认
					</view>
				</view>
			</view>

			<!-- 告警级别列表 -->
			<view class="filter-item">
				<view class="filter-title">告警级别</view>
				<view class="tag-options">
					<view 
						class="tag" 
						:class="{ active: selectedSeverity.includes('CRITICAL') }"
						@tap="toggleSeverity('CRITICAL')"
					>
						严重
					</view>
					<view 
						class="tag" 
						:class="{ active: selectedSeverity.includes('MAJOR') }"
						@tap="toggleSeverity('MAJOR')"
					>
						重要
					</view>
					<view 
						class="tag" 
						:class="{ active: selectedSeverity.includes('MINOR') }"
						@tap="toggleSeverity('MINOR')"
					>
						次要
					</view>
					<view 
						class="tag" 
						:class="{ active: selectedSeverity.includes('WARNING') }"
						@tap="toggleSeverity('WARNING')"
					>
						警告
					</view>
					<view 
						class="tag" 
						:class="{ active: selectedSeverity.includes('INDETERMINATE') }"
						@tap="toggleSeverity('INDETERMINATE')"
					>
						不确定
					</view>
				</view>
			</view>

			<!-- 告警类型列表 -->
			<view class="filter-item">
				<view class="filter-title">告警类型</view>
				<view class="type-select-wrapper">
					<image 
						src="/static/images/alarm-type.svg" 
						class="type-icon" 
						mode="aspectFit"
					></image>
					<uni-data-select
						v-model="selectedType"
						:localdata="typeOptions"
						placeholder="请选择告警类型"
						@change="onTypeChange"
						class="type-select"
					></uni-data-select>
					<image src="/static/images/arrow.svg" class="select-arrow" mode="aspectFit"></image>
				</view>
			</view>

			<!-- 受托人 -->
			<view class="filter-item">
				<text class="filter-label">受托人</text>
				<picker 
					@change="onAssigneeChange" 
					:value="assigneeIndex" 
					:range="assigneeList" 
					:range-key="'email'"
					class="picker"
				>
					<view class="picker-value">
						<view class="user-info">
							<view 
								class="avatar-circle"
								:style="{ backgroundColor: getAvatarColor(assigneeList[assigneeIndex]?.email) }"
							>
								{{ getInitial(assigneeList[assigneeIndex]?.email) }}
							</view>
							<text>{{ assigneeList[assigneeIndex]?.email || '请选择受托人' }}</text>
						</view>
						<image src="/static/images/arrow.svg" class="select-arrow" mode="aspectFit"></image>
					</view>
				</picker>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="footer">
			<view class="left-btn">
				<view class="btn reset" @tap="resetFilters">重置</view>
			</view>
			<view class="right-btns">
				<view class="btn cancel" @tap="goBack">取消</view>
				<view class="btn update" @tap="confirmFilter">更新</view>
			</view>
		</view>
	</view>
</template>

<style>
.alarm-search-container {
	min-height: 100vh;
	background-color: #fff;
	padding: 30rpx;
	padding-bottom: 120rpx;
	box-sizing: border-box;
	width: 100%;
	overflow-x: hidden;
}

.filter-item {
	margin-bottom: 40rpx;
	border: 1px solid #e0e0e0;
	border-radius: 12rpx;
	padding: 30rpx;
	box-sizing: border-box;
	width: 100%;
}

.filter-title {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 24rpx;
	padding: 0 10rpx;
}

.tag-options {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
	width: 100%;
	box-sizing: border-box;
}

.tag {
	padding: 16rpx 32rpx;
	background-color: #f5f5f5;
	border-radius: 8rpx;
	font-size: 28rpx;
	color: #333;
}

.tag.active {
	background-color: #305680;
	color: #fff;
}

.type-select,
.assignee-select {
	width: 100%;
	height: 80rpx;
	background-color: #f5f5f5;
	border-radius: 8rpx;
	padding: 0 30rpx;
	box-sizing: border-box;
}

.user-icon,
.arrow-icon {
	width: 40rpx;
	height: 40rpx;
}

.footer {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	display: flex;
	justify-content: space-between;
	padding: 30rpx;
	background-color: #fff;
	border-top: 1px solid #eee;
	box-sizing: border-box;
	width: 100%;
}

.left-btn {
	flex: 1;
	display: flex;
	justify-content: flex-start;
}

.right-btns {
	flex: 1;
	display: flex;
	justify-content: flex-end;
	gap: 20rpx;
}

.btn {
	width: 160rpx;
	height: 80rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 8rpx;
	font-size: 28rpx;
}

.reset {
	background-color: #f5f5f5;
	color: #305680;
}

.cancel {
	background-color: #f5f5f5;
	color: #333;
}

.update {
	background-color: #305680;
	color: #fff;
}

.update:active {
	opacity: 0.9;
}

.type-select {
	width: 100%;
	background-color: #f5f5f5;
	border-radius: 8rpx;
}

/* 可能需要覆盖 uni-data-select 的默认样式 */
.type-select :deep(.uni-select) {
	border: none !important;
	padding: 0 30rpx;
}

.type-select :deep(.uni-select__input-box) {
	height: 80rpx !important;
}

.type-select :deep(.uni-select__input-text) {
	font-size: 28rpx;
	color: #333;
	text-align: left;
	line-height: 80rpx;
}

.type-select :deep(.uni-select__input-placeholder) {
	font-size: 28rpx;
	color: #999;
	text-align: left;
}

.type-select :deep(.uni-select__input-box) {
	padding: 0 70rpx 0 30rpx !important;
	justify-content: flex-start !important;
}

.popup-content {
	background-color: #fff;
	border-radius: 24rpx 24rpx 0 0;
	padding-bottom: env(safe-area-inset-bottom);
}

.popup-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1px solid #eee;
}

.popup-title {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
}

.popup-close {
	font-size: 28rpx;
	color: #999;
}

.type-list {
	max-height: 600rpx;
}

.type-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1px solid #f5f5f5;
}

.active-text {
	color: #305680;
}

.check-icon {
	color: #305680;
	font-weight: bold;
}

.type-input {
	width: 100%;
	height: 80rpx;
	background-color: #f5f5f5;
	border-radius: 8rpx;
	padding: 0 30rpx;
	box-sizing: border-box;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.type-input input {
	flex: 1;
	height: 100%;
	font-size: 28rpx;
	color: #333;
}

.placeholder {
	color: #999;
}

.arrow-icon {
	width: 32rpx;
	height: 32rpx;
	margin-left: 20rpx;
}

.type-select-wrapper {
	position: relative;
	display: flex;
	align-items: center;
	background-color: #f5f5f5;
	border-radius: 8rpx;
	padding: 0 30rpx;
}

.type-icon {
	width: 56rpx;
	height: 56rpx;
	margin-right: 24rpx;
}

.type-select {
	flex: 1;
	height: 88rpx;
	line-height: 88rpx;
	font-size: 28rpx;
	background-color: transparent;
}

/* 覆盖 uni-data-select 的默认样式 */
:deep(.uni-data-select) {
	margin: 0;
	padding: 0;
	border: none;
}

:deep(.uni-data-select .uni-select) {
	border: none;
	padding: 0;
}

:deep(.uni-select__input-box) {
	height: 88rpx !important;
	line-height: 88rpx !important;
	padding: 0 !important;
}

:deep(.uni-select__input-text) {
	text-align: left !important;
	margin-left: 0 !important;
}

.select-arrow {
	position: absolute;
	right: 24rpx;
	top: 50%;
	transform: translateY(-50%);
	width: 32rpx;
	height: 32rpx;
}

/* 调整 select 的内边距，为箭头留出空间 */
.type-select :deep(.uni-select__input-box) {
	padding-right: 70rpx !important;
	padding-left: 0 !important;
}

.person-icon {
	position: absolute;
	left: 30rpx;
	top: 50%;
	transform: translateY(-50%);
	width: 32rpx;
	height: 32rpx;
	pointer-events: none;
}

/* 为受托人选择框添加左边距，为图标留出空间 */
.assignee-select :deep(.uni-select__input-box) {
	padding: 0 70rpx 0 30rpx !important;
}

/* 确保图标和文字垂直对齐 */
.type-select :deep(.uni-select__input-text) {
	display: flex;
	align-items: center;
}

/* 添加圆形头像样式 */
.avatar-circle {
	display: inline-block;
	width: 40rpx;
	height: 40rpx;
	line-height: 40rpx;
	border-radius: 50%;
	text-align: center;
	color: #ffffff;
	font-size: 24rpx;
	margin-right: 16rpx;
	font-weight: 500;
}

/* 调整下拉选项的样式 */
.type-select :deep(.uni-select__selector-item) {
	display: flex !important;
	align-items: center !important;
	padding: 20rpx 30rpx !important;
}

/* 确保选中值的显示正确 */
.type-select :deep(.uni-select__input-text) {
	display: flex !important;
	align-items: center !important;
}

/* 调整选项的hover效果 */
.type-select :deep(.uni-select__selector-item:hover) {
	background-color: #f5f5f5;
}

.picker {
	flex: 1;
	background-color: transparent;
	margin-top: 16rpx;
}

.picker-value {
	display: flex;
	justify-content: space-between;
	align-items: center;
	height: 88rpx;
	padding: 0 30rpx;
	background-color: #f5f5f5;
	border-radius: 8rpx;
	font-size: 28rpx;
	color: #333;
}

.user-info {
	display: flex;
	align-items: center;
	gap: 16rpx;
}

.avatar-circle {
	width: 48rpx;
	height: 48rpx;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #fff;
	font-size: 24rpx;
	font-weight: 500;
}

.filter-label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 24rpx;
	display: block;
}
</style>

<script>
import request from '@/utils/request.js'

export default {
	data() {
		return {
			selectedStatus: ['ACTIVE'],
			selectedSeverity: [],
			alarmTypes: [],        // 原始告警类型列表
			selectedType: '',      // 选中的告警类型
			typeLoading: false,    // 加载状态
			assignees: [],         // 原始受托人列表
			selectedAssignee: '',  // 选中的受托人
			assigneeLoading: false, // 加载状态
			assigneeList: [],      // 受托人列表
			assigneeIndex: 0,       // 选中的受托人索引
			// 添加一个变量保存初始筛选条件
			initialFilters: null
		}
	},
	computed: {
		// 转换数据格式以适配 uni-data-select
		typeOptions() {
			return this.alarmTypes.map(type => ({
				value: type,
				text: type
			}))
		},
		
		// 转换受托人数据格式以适配 uni-data-select
		assigneeOptions() {
			return this.assignees.map(user => {
				let text = ''
				if (user.email === '所有') {
					text = '👥 所有'
				} else if (user.email === '分配给我') {
					text = '🙋 分配给我'
				} else {
					text = '👤 ' + user.email  // 单个用户图标
				}
				return {
					value: user.id ? user.id.id : user.email,
					text: text
				}
			})
		}
	},
	onLoad() {
		// 获取上一页传递的筛选条件
		const eventChannel = this.getOpenerEventChannel()
		eventChannel.on('filterConditions', (data) => {
			if (data) {
				// 保存初始筛选条件
				this.initialFilters = data
				// 设置可以立即设置的条件
				this.selectedStatus = data.statusList || ['ACTIVE']
				this.selectedSeverity = data.severityList || []
				this.selectedType = data.typeList?.[0] || ''
			}
		})

		// 获取数据
		Promise.all([
			this.fetchAlarmTypes(),
			this.fetchAssignees(),
			this.fetchUsers()
		]).then(() => {
			// 所有数据加载完成后，设置受托人
			if (this.initialFilters?.assigneeId) {
				const index = this.assigneeList.findIndex(user => 
					user.id?.id === this.initialFilters.assigneeId
				)
				if (index > -1) {
					this.assigneeIndex = index
				}
			}
		})
	},
	methods: {
		toggleStatus(status) {
			const index = this.selectedStatus.indexOf(status)
			if (index > -1) {
				this.selectedStatus.splice(index, 1)
			} else {
				this.selectedStatus.push(status)
			}
		},
		
		toggleSeverity(severity) {
			const index = this.selectedSeverity.indexOf(severity)
			if (index > -1) {
				this.selectedSeverity.splice(index, 1)
			} else {
				this.selectedSeverity.push(severity)
			}
		},
		
		resetFilters() {
			this.selectedStatus = ['ACTIVE']
			this.selectedSeverity = []
			this.selectedType = ''
			this.assigneeIndex = 0  // 重置为第一个选项（全部）
			delete this.filterParams?.assigneeId  // 清除筛选条件中的assigneeId
		},
		
		goBack() {
			uni.navigateBack()
		},
		
		confirmFilter() {
			const eventChannel = this.getOpenerEventChannel()
			let assigneeId = null
			
			// 如果不是"全部"选项，则设置选中用户的ID
			if (this.assigneeIndex !== 0) {
				assigneeId = this.assigneeList[this.assigneeIndex].id.id
			}
			
			eventChannel.emit('acceptAlarmSearchConditions', {
				statusList: this.selectedStatus,
				severityList: this.selectedSeverity,
				typeList: this.selectedType ? [this.selectedType] : [],
				assigneeId: assigneeId
			})
			
			uni.navigateBack()
		},
		
		// 获取告警类型列表
		async fetchAlarmTypes() {
			if (this.typeLoading) return
			
			try {
				this.typeLoading = true
				const result = await request.get('/api/alarm/types', {
					pageSize: 25,
					page: 0
				})
				
				if (result && result.data) {
					// 只获取 type 字段
					this.alarmTypes = result.data.map(item => item.type)
				}
			} catch (error) {
				console.error('Failed to fetch alarm types:', error)
				uni.showToast({
					title: '获取告警类型失败',
					icon: 'none'
				})
			} finally {
				this.typeLoading = false
			}
		},
		
		// 选择告警类型
		onTypeChange(value) {
			this.selectedType = value
		},
		
		// 获取受托人列表
		async fetchAssignees() {
			if (this.assigneeLoading) return
			
			try {
				this.assigneeLoading = true
				const result = await request.get('/api/users/info', {
					pageSize: 50,
					page: 0,
					sortProperty: 'email',
					sortOrder: 'ASC'
				})
				
				if (result && result.data) {
					// 获取当前用户ID
					const userInfo = uni.getStorageSync('userInfo')
					const currentUserId = userInfo.userId
					
					result.data.push(
						{
							id: {
								entityType: "USER",
								id: null
							},
							email: '所有'
						},
						{
							id: {
								entityType: "USER",
								id: currentUserId  // 使用存储的用户ID
							},
							email: '分配给我'
						}
					)
					this.assignees = result.data
				}
			} catch (error) {
				console.error('Failed to fetch assignees:', error)
				uni.showToast({
					title: '获取受托人失败',
					icon: 'none'
				})
			} finally {
				this.assigneeLoading = false
			}
		},
		
		// 获取用户列表
		async fetchUsers() {
			try {
				const result = await request.get('/api/users', {
					pageSize: 100,
					page: 0
				})
				if (result && result.data) {
					this.assigneeList = [{ email: '全部' }, ...result.data]
					
					// 数据加载完成后，如果有初始筛选条件，设置受托人
					if (this.initialFilters?.assigneeId) {
						const index = this.assigneeList.findIndex(user => 
							user.id?.id === this.initialFilters.assigneeId
						)
						if (index > -1) {
							this.assigneeIndex = index
						}
					}
				}
			} catch (error) {
				console.error('获取用户列表失败：', error)
				uni.showToast({
					title: '获取用户列表失败',
					icon: 'none'
				})
			}
		},
		
		// 受托人选择变化
		onAssigneeChange(e) {
			this.assigneeIndex = e.detail.value
			// 更新筛选条件
			if (this.assigneeIndex === 0) {
				delete this.filterParams.assigneeId
			} else {
				this.filterParams.assigneeId = this.assigneeList[this.assigneeIndex].id.id
			}
		},
		
		// 获取邮箱首字母
		getInitial(email) {
			return email ? email.charAt(0).toUpperCase() : 'U'
		},
		
		// 获取头像背景色
		getAvatarColor(email) {
			if (!email || email === '全部') return '#999'
			const colors = ['#673AB7', '#2196F3', '#009688', '#4CAF50', '#FFC107']
			let hash = 0
			for (let i = 0; i < email.length; i++) {
				hash = email.charCodeAt(i) + ((hash << 5) - hash)
			}
			return colors[Math.abs(hash) % colors.length]
		}
	}
}
</script>
